package com.zj.osm.view.map.line

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.zj.osm.App
import com.zj.osm.R
import com.zj.osm.entity.db.LineDao
import com.zj.osm.entity.db.PointDao
import com.zj.osm.entity.greendao.Equipment
import com.zj.osm.entity.greendao.Line
import com.zj.osm.entity.greendao.Point
import com.zj.osm.model.pojo.Equip
import com.zj.osm.model.pojo.Module
import com.zj.osm.model.pojo.ModuleType
import com.zj.osm.utils.SQLiteDatabaseUtils
import com.zj.osm.utils.db_utils.LineUtils
import com.zj.osm.view.BaseActivity
import com.zj.osm.view.map.map.MapActivity
import com.zj.utils.utils.SpinnerUtils.setSpinnerItemSelectedByValue
import io.reactivex.annotations.NonNull
import kotlinx.android.synthetic.main.activity_equ.*
import kotlinx.android.synthetic.main.line_type_xiugai.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.*

/**
 * 修改线属性的活动
 */
class LineActivity : BaseActivity(), View.OnClickListener {
    var modulesList: List<Module?> = ArrayList<Module?>()
    private var context: Context? = null
    private var line_sp_sort: Spinner? = null
    private var line_sp_type: Spinner? = null
    private var line_sp_statue: Spinner? = null
    private var line_sp_a: Spinner? = null
    private var line_sp_b: Spinner? = null
    private var line_tv_dj: EditText? = null
    private var line_tv_line_hui: EditText? = null
    private var line_tv_line_gen: EditText? = null
    private var currentLine: Line? = null
    private val allMT: MutableList<ModuleType> = ArrayList<ModuleType>()
    private val mtAllSet: MutableSet<ModuleType> = HashSet<ModuleType>()
    private var equip: Equip? = null
    private var lineSpLaying: Spinner? = null
    private var lineRlLaying: RelativeLayout? = null
    private lateinit var lineTvName: EditText
    private lateinit var mLineListView: RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_line)
        context = this
        val intent: Intent = getIntent()
        currentLine = intent.getParcelableExtra("line")
        assert(currentLine != null)
        initView()
        //initViewData();
    }

    fun getGuPiaoDai(str: Int): List<Equip?> {
        val strings: MutableList<Equip?> = ArrayList<Equip?>()
        val db: SQLiteDatabase = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        @SuppressLint("Recycle") val cursor = db.rawQuery("select * from EquipType where component=$str order by ID", null) //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            val equip = Equip()
            equip.setId(cursor.getInt(0))
            equip.setName(cursor.getString(1))
            equip.setCode(cursor.getString(4))
            strings.add(equip)
        }
        cursor.close()

        return strings
    }

    var isFist = 0

    /**
     * 初始化数据
     */
    @SuppressLint("SetTextI18n")
    private fun initViewData() {
        val line_btn_save: Button = findViewById(R.id.line_btn_save)
        setSpinnerItemSelectedByValue(line_sp_sort, currentLine!!.type)
        setSpinnerItemSelectedByValue(line_sp_statue, currentLine!!.state)
        val ptA: Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(currentLine!!.start_id)).build().unique()
        val ptB: Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(currentLine!!.end_id)).build().unique()
        //List<Equipment> equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(currentLine.getId()), EquipmentDao.Properties.Qubie.eq(1)).build().list();
        if (ptA != null) {
            val k = line_sp_a!!.count
            for (i in 0 until k) {
                val vaule: Point = line_sp_a!!.adapter.getItem(i) as Point
                if (ptA.getUid().equals(vaule.getUid())) {
                    line_sp_a!!.setSelection(i, true) // 默认选中项
                    break
                }
            }
        }
        if (ptB != null) {
            val k = line_sp_b!!.count
            for (i in 0 until k) {
                val vaule: Point = line_sp_b!!.adapter.getItem(i) as Point
                if (ptB.getUid().equals(vaule.getUid())) {
                    line_sp_b!!.setSelection(i, true) // 默认选中项
                    break
                }
            }
        }
        line_tv_dj!!.setText(currentLine!!.length.toString() + "")
        line_tv_line_hui!!.setText(currentLine!!.backNum)
        //LinearLayout linearLayout = getWindow().getDecorView().findViewById(R.id.line_ll);
//添加的设备不为空时，添加新的View
/*if (equipmentList.size() > 0) {
            linearLayout.removeAllViews();
            for (int i = 0; i < equipmentList.size(); i++) {
                Log.e("TAG", "addLinearLayout: " + equipmentList.size());
                View view = View.inflate(context, R.layout.activity_equ_equ, null);
                TextView equ_ed_lever = view.findViewById(R.id.equ_ed_lever);
                TextView equ_tv_name = view.findViewById(R.id.equ_tv_name);
                TextView equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
                TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
                Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);
                equ_tv_name.setText(equipmentList.get(i).getName());
                equ_ed_lever.setText(equipmentList.get(i).getThree_name());
                equ_tv_amount.setText(equipmentList.get(i).getAmount() == 0 ? "" : equipmentList.get(i).getAmount() + "");
                linearLayout.addView(view);
                final int finalI = i;
                equ_btn_delete.setOnClickListener(v -> {

                    if (equipmentList.size() > 1) {
                        App.getInstances().getDaoSession().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                        initViewData();
                    } else {
                        App.getInstances().getDaoSession().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                        linearLayout.removeAllViews();
                    }
                });
                equ_tv_xuan.setOnClickListener(v -> addEqu(equipmentList.get(finalI)));
            }
        }*/
    }

    /**
     * 按钮点击事件
     */
    override fun onClick(v: View) {
        when (v.id) {
            R.id.line_btn_save -> finish()
            R.id.activity_ib_back -> {
                MapActivity.isProgressShow = false
                finish()
            }
            R.id.activity_tv_save -> {
                MapActivity.isProgressShow = false
                finish()
            }
            R.id.equ_btn_equ ->  /*if (equip.getId() == 11) {
                    ToastUtils.showShort("架空线路暂时无设备添加");
                } else {
                }*/addEqu(null)
            R.id.map_btn_cancell -> {
                MapActivity.isProgressShow = false
                finish()
            }
        }
    }

    override fun onBackPressed() {
        MapActivity.isProgressShow = false
        super.onBackPressed()
    }

    private fun getAllSubModuleType(mt: ModuleType): Set<ModuleType> {
        mtAllSet.add(mt)
        val db: SQLiteDatabase = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        @SuppressLint("Recycle") val cursor = db.rawQuery("select mt.* from moduletype mt where mt.ParentKey = " + "'" + mt.getModuleTypeKey() + "'", null) //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            val moduleType = ModuleType()
            moduleType.setModuleTypeID(cursor.getString(0))
            moduleType.setName(cursor.getString(1))
            moduleType.setModuleTypeKey(cursor.getString(2))
            moduleType.setParentKey(cursor.getString(3))
            getAllSubModuleType(moduleType)
        }
        cursor.close()

        return mtAllSet
    }

    private fun getModuleAll(mt: ModuleType): List<Module?> {
        mtAllSet.clear()
        val mtAll: Set<ModuleType> = getAllSubModuleType(mt)
        val mAll: MutableList<Module?> = ArrayList<Module?>()
        val db: SQLiteDatabase = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        for (m in mtAll) {
            @SuppressLint("Recycle") val cursor = db.rawQuery("select m.* from module m where m.moduletypekey = " + "'" + m.getModuleTypeKey() + "'", null) //此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                val mod = Module()
                mod.setModuleID(cursor.getString(0))
                mod.setModuleName(cursor.getString(1))
                mod.setModuleTypeKey(cursor.getString(2))
                mod.setModuleCode(cursor.getString(3))
                mAll.add(mod)
            }
            cursor.close()
        }

        return mAll
    }



    /**
     * 查找与本条线路关联的线段
     *
     * @param line  /
     * @param isAll (true查询所有线段,false只查询与拐点关联线段)
     * @return 返回所有线段
     */
    private fun getRelationLine(line: Line?, isAll: Boolean): Set<Line> {
        val lineSet: MutableSet<Line> = HashSet()
        return getRelationLine(line, isAll, lineSet)
    }

    /**
     * 查找与本条线路关联的线段
     *
     * @param line    xian
     * @param isAll   (true查询所有线段,false只查询与“拐点”关联线段)
     * @param lineSet (可用于存放结果的容器,中介者)
     * @return 返回所有线段
     */
    private fun getRelationLine(line: Line?, isAll: Boolean, lineSet: MutableSet<Line>): Set<Line> {
        Log.e("linexiugai=", line.toString())
        val pointlst: List<Point> = App.getInstances().getDaoSession().getPointDao().queryBuilder().whereOr(PointDao.Properties.Uid.eq(line!!.start_id), PointDao.Properties.Uid.eq(line.end_id)).build().list()
        for (p in pointlst) {
            if (p.getName().contains("拐点") || isAll) {
                val lines: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().whereOr(LineDao.Properties.Start_id.eq(p.getUid()), LineDao.Properties.End_id.eq(p.getUid())).build().list()
                for (index in lines.indices) {
                    if (!lineSet.contains(lines[index])) {
                        if (lines[index].methodName == null) {
                            lineSet.add(lines[index])
                            Log.e("linexiugaiIn=", lines[index].toString())
                            getRelationLine(lines[index], isAll, lineSet)
                        }
                    }
                }
            }
        }
        return lineSet
    }

    var xuanxinList: MutableList<Line> = ArrayList()

    private fun initView() {
        Log.e("lines1=====", currentLine.toString())
        line_btn_saves = findViewById(R.id.line_btn_save)
        line_btn_saves!!.setOnClickListener(this)
        lineLuMokuai = findViewById(R.id.lineLuMokuai)
        addLineSave = findViewById(R.id.addLineSave)
        addLineSave!!.setOnClickListener { v: View? ->
            Log.e("124=====", xuanxinList.toString())
            if (xuanxinList.size > 0) {
                val LineWf = xuanxinList[0]
                Log.e("xuanxinList=====", xuanxinList.toString())
                val newLineWf = Line()
                newLineWf.cid = getUUID()
                newLineWf.start_id = LineWf.start_id
                newLineWf.end_id = LineWf.end_id
                newLineWf.name = LineWf.name
                newLineWf.type = LineWf.type
                newLineWf.types = LineWf.types
                newLineWf.pipe_laying_state = (LineWf.pipe_laying_state)
                newLineWf.state = (LineWf.state)
                newLineWf.typeId = (LineWf.typeId)
                newLineWf.backNum = LineWf.backNum
                newLineWf.num = LineWf.num
                newLineWf.methodName = LineWf.methodName
                newLineWf.line_len = LineWf.line_len
                newLineWf.item_id = LineWf.item_id
                newLineWf.latA = LineWf.latA
                newLineWf.latB = LineWf.latB
                newLineWf.lonA = LineWf.lonA
                newLineWf.lonB = LineWf.lonB
                newLineWf.name_a = LineWf.name_a
                newLineWf.name_b = LineWf.name_b
                newLineWf.length = LineWf.length
                newLineWf.moduleID = LineWf.moduleID
                newLineWf.path = LineWf.path
                newLineWf.name_b = LineWf.name_b
                newLineWf.length = LineWf.length
                newLineWf.moduleID = LineWf.moduleID
                newLineWf.moduleTxt = LineWf.moduleTxt
                newLineWf.path = LineWf.path
                newLineWf.parallelPole = LineWf.parallelPole
                newLineWf.legendTypeKey = LineWf.legendTypeKey
                newLineWf.id = null
                //这里计算所有的线路名称
//获取所有的线路去除过同样名称的个数就是所有线的编号。
                val unitAllLine: MutableList<String> = ArrayList()
                val allLine: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(currentLine!!.item_id)).list()
                for (i in allLine.indices) {
                    if (!unitAllLine.contains(allLine[i].name)) {
                        unitAllLine.add(allLine[i].name)
                    }
                }
                val line_names = "线路" + LineUtils.getInstance().getInLinesMaxNumber(currentLine!!.item_id).toString() + "#"
                newLineWf.name = line_names
                val currentId: Long = App.getInstances().getDaoSession().getLineDao().insert(newLineWf)
                newLineWf.id = currentId
                //newLineWf.setName(currentId + "#");
                App.getInstances().getDaoSession().getLineDao().update(newLineWf)
                //newLineWf.setName((xuanxinList.size()+1)+"#");
                xuanxinList.add(newLineWf)
                buiLuNameber!!.text = xuanxinList.size.toString() + "回路"
                mHandler.postDelayed({ linesAdapter?.notifyDataSetChanged() }, 200)
                if (xuanxinList.size >= 3) {
                    addLineSave!!.visibility = View.GONE
                } else {
                    addLineSave!!.visibility = View.VISIBLE
                }
            }
        }
        buiLuNameber = findViewById(R.id.huiLuNumber)
        mLineListView = findViewById(R.id.mLineListView)
        //这里查询所有的线
        val gulianLineCurrent: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(currentLine!!.start_id), LineDao.Properties.End_id.eq(currentLine!!.end_id)).build().list()
        val gulianLineOther: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(currentLine!!.end_id), LineDao.Properties.End_id.eq(currentLine!!.start_id)).build().list()
        xuanxinList.addAll(gulianLineCurrent)
        xuanxinList.addAll(gulianLineOther)
        Log.e("allLinex", xuanxinList.toString())
        if (xuanxinList.size >= 3) {
            addLineSave!!.visibility = View.GONE
        } else {
            addLineSave!!.visibility = View.VISIBLE
        }
        buiLuNameber!!.text = xuanxinList.size.toString() + "回路"
        xiugaiLinePopWindows(xuanxinList[0])
//        linesAdapter = LinesAdapter()
//        mLineListView.adapter = linesAdapter
//        linesAdapter?.notifyDataSetChanged()
//        val linearLayoutManager = LinearLayoutManager(context)
//        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL)
//        mLineListView.layoutManager = linearLayoutManager

        val activity_ib_back: ImageButton = findViewById(R.id.activity_ib_back)
        val map_btn_cancell: Button = findViewById(R.id.map_btn_cancell)
        activity_ib_back.setOnClickListener(this)
        map_btn_cancell.setOnClickListener(this)
        val activity_tv_title: TextView = findViewById(R.id.activity_tv_title)
        activity_tv_title.text = "线路"
        val activity_tv_save: TextView = findViewById(R.id.activity_tv_save)
        activity_tv_save.setText(getString(R.string.map_quxiao))
        activity_tv_save.setOnClickListener(this)
        val equ_btn_equ: TextView = findViewById(R.id.equ_btn_equ)
        equ_btn_equ.setOnClickListener(this)
        lineTvName = findViewById(R.id.lineTvName)
        lineSpLaying = findViewById(R.id.lineSpLaying)
        lineRlLaying = findViewById(R.id.lineRlLaying)
        line_sp_sort = findViewById(R.id.line_sp_sort)
        line_sp_type = findViewById(R.id.line_sp_type)
        line_sp_statue = findViewById(R.id.line_sp_statue)
        /*line_sp_a = findViewById(R.id.line_sp_a)
        line_sp_b = findViewById(R.id.line_sp_b)*/
        //line_tv_dj = findViewById(R.id.line_tv_dj)
        line_tv_line_hui = findViewById(R.id.line_tv_line_hui)
        line_tv_line_gen = findViewById(R.id.line_tv_line_gen)
        val equipList: List<Equip?> = getGuPiaoDai(3)
        Log.e("equipList", equipList.toString())
        //适配器
        val adapter: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this, android.R.layout.simple_spinner_item, equipList)
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        line_sp_sort!!.adapter = adapter
        if (line_sp_sort!!.selectedItem.toString().contains("电缆")) {
            lineRlLaying!!.visibility = View.VISIBLE
        } else {
            lineRlLaying!!.visibility = View.GONE
        }
        if (currentLine!!.path != null && !currentLine!!.path.equals("")) {
            Log.e("pathName", currentLine!!.path)
            val linePath: Array<String> = getResources().getStringArray(R.array.laying)
            for (i in linePath.indices) {
                if (linePath[i].contains(currentLine!!.path.trim())) {
                    Log.e("pathName", currentLine!!.path + i)
                    lineSpLaying!!.setSelection(i)
                    break
                }
            }
        } else {
            setSpinnerItemSelectedByValue(lineSpLaying, "高压架空线路")
            line_tv_line_gen!!.setText("3")
            line_tv_line_gen!!.isEnabled = false
        }
        line_sp_sort!!.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                equip = line_sp_sort!!.selectedItem as Equip
                modulesList = com.zj.osm.utils.db_utils.ModuleUtils.getInstance().getModuleList(equip!!.getId())
                //适配器
                val arr_adapter4: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this@LineActivity, android.R.layout.simple_spinner_item, modulesList)
                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                line_sp_type!!.adapter = arr_adapter4
                if (currentLine!!.types != null) {
                    setSpinnerItemSelectedByValue(line_sp_type, currentLine!!.types)
                }
                if (line_sp_sort!!.selectedItem.toString().contains("电缆")) {
                    lineRlLaying!!.visibility = View.VISIBLE
                } else {
                    lineRlLaying!!.visibility = View.GONE
                }
                if (equip?.getName().equals("高压架空线路")) {
                    line_tv_line_gen!!.setText("3")
                    line_tv_line_gen!!.isEnabled = false
                } else if (equip?.getName().equals("低压架空线路")) {
                    line_tv_line_gen!!.setText("4")
                    line_tv_line_gen!!.isEnabled = false
                } else {
                    line_tv_line_gen!!.setText(currentLine!!.num)
                    line_tv_line_gen!!.isEnabled = true
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        line_sp_type!!.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                Log.e("TAG", "onItemSelectessd: " + modulesList[position]!!.toStrings())
                //如果是电缆，显示敷设方式。否则不显示
                if (modulesList[position]!!.getRemark() != null && !modulesList[position]!!.getRemark().equals("")) {
                    Log.e("pathName2", modulesList[position]!!.getRemark())
                    setSpinnerItemSelectedByValue(lineSpLaying, modulesList[position]!!.getRemark())
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        lineTvName!!.setText(currentLine!!.name)
        val PointList: List<Point?> = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(currentLine!!.projectId)).build().list()
        Log.e("poiintListString=", PointList.toString());
        //适配器
        /* val sp_adapter: ArrayAdapter<Point> = ArrayAdapter<Point>(this, android.R.layout.simple_spinner_item, PointList)
         sp_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
         line_sp_a!!.adapter = sp_adapter
         line_sp_b!!.adapter = sp_adapter
         if (currentLine!!.moduleTxt != null && !currentLine!!.moduleTxt.equals("")) {
             setSpinnerItemSelectedByValue(line_sp_type, currentLine!!.moduleTxt)
         }*/
    }

    /**
     * 添加附属设备点点id查询equip_modleType里面的
     *
     * @param equId id
     * @return 子类集合
     */
    private fun getFushuEquipId(equId: Int): List<ModuleType?> {
        val moduleTypeData: MutableList<ModuleType?> = ArrayList<ModuleType?>()
        val db: SQLiteDatabase = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        @SuppressLint("Recycle") val cursor: Cursor
        Log.e("sqlpoint1=", "select mt.* from moduletype mt left join \"equip_moduleType_ Attached\" ematt on mt.ModuleTypeID = ematt.ModuletypeID where ematt.equipTypeID = $equId")
        cursor = db.rawQuery("select mt.* from moduletype mt left join equip_moduleType ematt on mt.ModuleTypeID = ematt.ModuletypeID where ematt.equipID = $equId", null) //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            val moduleType = ModuleType()
            moduleType.setModuleTypeID(cursor.getString(0))
            moduleType.setName(cursor.getString(1))
            moduleType.setModuleTypeKey(cursor.getString(2))
            moduleType.setParentKey(cursor.getString(3))
            //moduleType.setState(cursor.getString(4));
            moduleTypeData.add(moduleType)
        }
        cursor.close()

        return moduleTypeData
    }

    private fun getTypeClass(selMt: ModuleType): List<ModuleType?> {
        val mtLst: MutableList<ModuleType?> = ArrayList<ModuleType?>()
        val db: SQLiteDatabase = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        @SuppressLint("Recycle") val cursor = db.rawQuery("select mt.* from ModuleType mt where mt.ParentKey = " + "'" + selMt.getModuleTypeKey() + "'", null) //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            val moduleType = ModuleType()
            moduleType.setModuleTypeID(cursor.getString(0))
            moduleType.setName(cursor.getString(1))
            moduleType.setModuleTypeKey(cursor.getString(2))
            moduleType.setParentKey(cursor.getString(3))
            //moduleType.setState(cursor.getString(4));
            mtLst.add(moduleType)
        }
        cursor.close()

        return mtLst
    }

    /**
     * 添加设备
     */
    private fun addEqu(equipment: Equipment?) {
        val views = View.inflate(context, R.layout.activity_equ_dialog, null)
        val map_ed_lever = views.findViewById<Spinner>(R.id.map_ed_lever)
        val map_ed_head = views.findViewById<Spinner>(R.id.map_ed_head)
        val map_sp_three = views.findViewById<Spinner>(R.id.map_sp_three)
        val map_ed_four = views.findViewById<EditText>(R.id.map_ed_four)
        val map_btn_quxiao = views.findViewById<Button>(R.id.map_btn_quxiao)
        val map_btn_queding = views.findViewById<Button>(R.id.map_btn_queding)
        val map_tv_title = views.findViewById<TextView>(R.id.map_tv_title)
        val moduleTypeList: List<ModuleType?> = getFushuEquipId(equip!!.getId())
        map_tv_title.text = "设备"
        Log.e("moduleTypeList", equip?.getId().toString() + "")
        //适配器
        val adapter: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this, android.R.layout.simple_spinner_item, moduleTypeList)
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        map_ed_lever.adapter = adapter
        map_ed_lever.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                val typeClass: List<ModuleType?> = getTypeClass(map_ed_lever.selectedItem as ModuleType)
                if (typeClass.size > 0) {
                    val arr_adapter4: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this@LineActivity, android.R.layout.simple_spinner_item, typeClass)
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                    map_ed_head.adapter = arr_adapter4
                    for (mt in typeClass) {
                        if (mt!!.getModuleTypeID().trim().equals((if (equipment == null) "" else equipment.getHead_id().toString() + "").trim { it <= ' ' })) {
                            map_ed_head.setSelection(typeClass.indexOf(mt))
                            break
                        }
                    }
                    map_ed_head.visibility = View.VISIBLE
                    map_ed_head.onItemSelectedListener = object : OnItemSelectedListener {
                        override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                            val mds: List<Module?> = getModuleAll(map_ed_head.selectedItem as ModuleType)
                            if (mds.size > 0) {
                                map_sp_three.visibility = View.VISIBLE
                                val arr_adapter4: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this@LineActivity, android.R.layout.simple_spinner_item, mds)
                                //设置样式
                                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                map_sp_three.adapter = arr_adapter4
                                if (equipment != null && equipment.threeName != null) {
                                    setSpinnerItemSelectedByValue(map_sp_three, equipment.threeName)
                                }
                                for (mt in mds) {
                                    if (mt?.moduleID?.trim().equals(if (equipment == null) "" else (equipment.getModuleID().toString() + "").trim())) {
                                        map_sp_three.setSelection(mds.indexOf(mt))
                                        break
                                    }
                                }
                            } else {
                                map_sp_three.visibility = View.GONE
                            }
                        }

                        override fun onNothingSelected(parent: AdapterView<*>?) {}
                    }
                } else {
                    val mds: List<Module?> = getModuleAll(map_ed_lever.selectedItem as ModuleType)
                    val arr_adapter4: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this@LineActivity, android.R.layout.simple_spinner_item, mds)
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                    map_sp_three.adapter = arr_adapter4
                    if (equipment != null) {
                        setSpinnerItemSelectedByValue(map_sp_three, equipment.threeName)
                    }
                    for (mt in mds) {
                        if (mt!!.getModuleID().trim().equals(if (equipment == null) "" else (equipment.getModuleID().toString() + "").trim())) {
                            map_sp_three.setSelection(mds.indexOf(mt))
                            break
                        }
                    }
                    map_ed_head.visibility = View.GONE
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        val dialog = AlertDialog.Builder(context).create()
        dialog.setView(views)
        dialog.show()
        map_btn_quxiao.setOnClickListener { view: View? ->
            KeyboardUtils.hideSoftInput(views)
            dialog.dismiss()
        }
        //确定按钮
        map_btn_queding.setOnClickListener { v: View? ->
            KeyboardUtils.hideSoftInput(views)
            dialog.dismiss()
            val levelMT: ModuleType = map_ed_lever.selectedItem as ModuleType
            if (equipment == null) { //这里是新增
                val myequip = Equipment()
                myequip.setLever_id(levelMT.getModuleTypeID())
                //myequip.setLever_id(levelMT.getModuleTypeKey());
                myequip.setModule_code(levelMT.getModuleCode())
                myequip.setName(levelMT.getName())
                val threeMT: Module = map_sp_three.selectedItem as Module
                //如果第二级显示
                if (map_ed_head.visibility == View.VISIBLE) { //给一级负值
                    val headLMT: ModuleType = map_ed_head.selectedItem as ModuleType
                    //给二级负值
                    myequip.setHead_id(headLMT.getModuleTypeID().trim())
                    //myequip.setHead_id(headLMT.getModuleTypeKey());
                    myequip.twoName = (headLMT.getName())
                } else {
                    myequip.setHead_id("0")
                    myequip.twoName = ("")
                }
                //三级赋值
//Log.e(TAG, "onClick:水水水水ss "+threeMT.toStrings() );
                if (threeMT != null) {
                    myequip.threeId = (threeMT.getModuleID())
                    myequip.threeName = (threeMT.getModuleName())
                } else {
                    ToastUtils.showShort("所选设备配置不全")
                    return@setOnClickListener
                    //if (myequip.getThree_name()==null) {
/*myequip.setThree_id("0");
                        myequip.setThree_name("");*/
//}
                }
                myequip.setQubie(1)
                myequip.setAmount(if (map_ed_four.text == null || map_ed_four.text.toString().trim { it <= ' ' } == "") 1 else map_ed_four.text.toString().trim { it <= ' ' }.toInt())
                //myequip.setItemID(id);
                myequip.pointId = (currentLine!!.id)
                App.getInstances().getDaoSession().getEquipmentDao().insert(myequip)
            } else { //修改
                equipment.setLever_id(levelMT.getModuleTypeID())
                //equipment.setLever_id(levelMT.getModuleTypeKey());
                equipment.setName(levelMT.getName())
                //如果第二级显示
                if (map_ed_head.visibility == View.VISIBLE) { //给一级负值
                    val headLMT: ModuleType = map_ed_head.selectedItem as ModuleType
                    //给二级负值
                    equipment.setHead_id(headLMT.getModuleTypeID().trim())
                    //equipment.setHead_id(headLMT.getModuleTypeKey());
                    equipment.twoName = (headLMT.getName())
                } else {
                    equipment.setHead_id("0")
                    equipment.twoName = ("")
                }
                //三级赋值
                val threeMT: Module = map_sp_three.selectedItem as Module
                if (threeMT != null) {
                    equipment.threeId = (threeMT.getModuleID())
                    equipment.threeName = (threeMT.getModuleName())
                } else {
                    ToastUtils.showShort("所选设备配置不全")
                    return@setOnClickListener
                    /*equip.setThree_id("0");
                    equip.setThree_name("");*/
                }
                equipment.setQubie(1)
                equipment.setAmount(if (map_ed_four.text == null || map_ed_four.text.toString().trim { it <= ' ' } == "") 1 else map_ed_four.text.toString().trim { it <= ' ' }.toInt())
                //equipment.setItemID(id);
                equipment.pointId = (currentLine!!.id)
                App.getInstances().getDaoSession().getEquipmentDao().update(equipment)
            }
            initViewData()
        }
    }

    ///查询线的remark
    private fun getLineRemarker(reMarkerName: String): String {
        var ReMark = ""
        Log.e("curseor6", "进入了")
        val db: SQLiteDatabase = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        Log.e("sql=", "select * from EquipType  where name='$reMarkerName'")
        @SuppressLint("Recycle") val cursor = db.rawQuery("select * from EquipType  where name='$reMarkerName'", null) //此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ReMark = cursor.getString(6)
        }
        cursor.close()

        Log.e("remark", ReMark)
        return ReMark
    }

    inner class LinesAdapter : RecyclerView.Adapter<LinesAdapter.ViewHolder?>() {
        @NonNull
        override fun onCreateViewHolder(parent: ViewGroup, i: Int): ViewHolder {
            val convertView = LayoutInflater.from(context).inflate(R.layout.activity_lines_item, null)
            return ViewHolder(convertView)
        }

        override fun onBindViewHolder(@NonNull viewHolder: ViewHolder, position: Int) {
            viewHolder.lineXuanxing.text = if (xuanxinList[position].types == null || xuanxinList[position].types.isEmpty()) "设置值" else xuanxinList[position].types
            viewHolder.lineStateTv.setText(xuanxinList[position].state)
            viewHolder.lineNameTv.text = xuanxinList[position].name
            if (xuanxinList[position].type != null && !xuanxinList[position].type.isEmpty()) {
                viewHolder.lineLiebieTv.text = xuanxinList[position].type.replace("线路", "")
            }
            val ptA: Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(xuanxinList[position].start_id)).build().unique()
            val ptB: Point = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(xuanxinList[position].end_id)).build().unique()
            if (ptA != null && ptA.getName() != null && ptA.getMark() != null) {
                viewHolder.lineGlName.text = "始：" + ptA.getName() + ptA.getMark()
            }
            if (ptB != null && ptB.getName() != null && ptB.getMark() != null && ptB != null) {
                viewHolder.linezGlName.text = "终：" + ptB.getName() + ptB.getMark()
            }
            if (xuanxinList[position].parallelPole != null && xuanxinList[position].parallelPole.equals("同杆并架")) {
                viewHolder.tongganBingjia.text = xuanxinList[position].parallelPole
            }
            viewHolder.lineGlDangjuName.text = xuanxinList[position].length
            viewHolder.xiugaiTv.setOnClickListener { v: View? -> xiugaiLinePopWindows(xuanxinList[position]) }
            if (xuanxinList.size > 1) {
                viewHolder.xiugaiDeTv.visibility = View.VISIBLE
            } else {
                viewHolder.xiugaiDeTv.visibility = View.GONE
            }
            viewHolder.xiugaiDeTv.setOnClickListener { v: View? ->
                if (xuanxinList.size > 1) {
                    val dialog = NormalDialog(this@LineActivity)
                    dialog.content("确定删除?") //
                            .style(NormalDialog.STYLE_TWO) //
                            .btnNum(2)
                            .title("删除线选型")
                            .btnText("取消", "删除") //
                            .show()
                    dialog.setOnBtnClickL(OnBtnClickL { dialog.dismiss() }, OnBtnClickL {
                        dialog.dismiss()
                        App.getInstances().getDaoSession().getLineDao().delete(xuanxinList[position])
                        xuanxinList.remove(xuanxinList[position])
                        if (xuanxinList.size >= 3) {
                            addLineSave!!.visibility = View.GONE
                        } else {
                            addLineSave!!.visibility = View.VISIBLE
                        }
                        buiLuNameber!!.text = xuanxinList.size.toString() + "回路"
                        notifyDataSetChanged()
                    })
                } else {
                    ToastUtils.showShort("不能删除")
                }
            }
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        inner class ViewHolder(@NonNull rootView: View) : RecyclerView.ViewHolder(rootView) {
            var lineXuanxing: TextView
            var lineStateTv: TextView
            var lineNameTv: TextView
            var lineLiebieTv: TextView
            var xiugaiTv: TextView
            var xiugaiDeTv: TextView
            var lineState: TextView? = null
            var lineGlName: TextView
            var lineGlDangjuName: TextView
            var linezGlName: TextView
            var tongganBingjia: TextView

            init {
                lineXuanxing = rootView.findViewById(R.id.lineXuanxing)
                lineStateTv = rootView.findViewById(R.id.lineState)
                lineNameTv = rootView.findViewById(R.id.lineName)
                lineLiebieTv = rootView.findViewById(R.id.lineLiebie)
                xiugaiTv = rootView.findViewById(R.id.xiugaiTv)
                xiugaiDeTv = rootView.findViewById(R.id.xiugaiDeTv)
                linezGlName = rootView.findViewById(R.id.linezGlName)
                //lineState = rootView.findViewById(R.id.lineState);
                lineGlName = rootView.findViewById(R.id.lineGlName)
                lineGlDangjuName = rootView.findViewById(R.id.lineGlDangjuName)
                tongganBingjia = rootView.findViewById(R.id.tongganBingjia)
            }
        }

        override fun getItemCount(): Int {
            return xuanxinList.size;
        }
    }

    private var map_btn_cancell: Button? = null
    private var line_btn_saves: Button? = null
    private var line_btn_save: Button? = null
    private var line_tongdao_statue: Spinner? = null

    private lateinit var srcNetureSpiner: Spinner
    private lateinit var srcNetureTypeSpiner: Spinner


    private lateinit var roadZcEt:EditText
    private lateinit var roadAdress:EditText
    private lateinit var gridNameLineEt:EditText
    private lateinit var zjcjgTv:EditText
    private lateinit var resultCaculateHols:TextView
    private lateinit var resultHolesTv:TextView
    private lateinit var numberOfPowerHoles:TextView

    private lateinit var lineNumberEt:EditText
    private lateinit var shenyuNumber:EditText
    private lateinit var srcStateSp:Spinner
    private lateinit var ghYear:EditText


    private fun xiugaiLinePopWindows(isLine: Line) {
        Log.e("linelllllllll1=", isLine.toString())
        val viewLine = View.inflate(context, R.layout.line_type_xiugai, null)
        val equ_btn_equ = viewLine.findViewById<TextView>(R.id.equ_btn_equ)
        equ_btn_equ.setOnClickListener(this)
        line_btn_save = viewLine.findViewById(R.id.line_btn_save)
        lineTvName = viewLine.findViewById(R.id.lineTvName)
        map_btn_cancell = viewLine.findViewById(R.id.map_btn_cancell)
        lineSpLaying = viewLine.findViewById(R.id.lineSpLaying)
        lineRlLaying = viewLine.findViewById(R.id.lineRlLaying)
        line_sp_sort = viewLine.findViewById(R.id.line_sp_sort)
        line_sp_type = viewLine.findViewById(R.id.line_sp_type)
        line_sp_statue = viewLine.findViewById(R.id.line_sp_statue)
        line_sp_a = viewLine.findViewById(R.id.line_sp_a)
        line_sp_b = viewLine.findViewById(R.id.line_sp_b)
        line_tv_dj = viewLine.findViewById(R.id.line_tv_dj)
        line_tongdao_statue = viewLine.findViewById(R.id.line_tongdao_statue)
        line_tv_line_hui = viewLine.findViewById(R.id.line_tv_line_hui)
        line_tv_line_gen = viewLine.findViewById(R.id.line_tv_line_gen)
        //region湖南
        val roadStarTv: TextView = viewLine.findViewById(R.id.roadStarTv)
        val roadEndTv: TextView = viewLine.findViewById(R.id.roadEndTv)
        roadAdress = viewLine.findViewById(R.id.roadAdress)
        gridNameLineEt=viewLine.findViewById(R.id.gridNameLineEt)
        zjcjgTv = viewLine.findViewById(R.id.zjcjgTv)

        roadZcEt = viewLine.findViewById(R.id.roadZcEt)
        srcNetureTypeSpiner = viewLine.findViewById(R.id.srcNetureTypeSpiner)
        srcNetureSpiner = viewLine.findViewById(R.id.srcNetureSpiner)
        resultCaculateHols = viewLine.findViewById(R.id.resultCaculateHols)
        resultHolesTv      = viewLine.findViewById(R.id.resultHolesTv)
        numberOfPowerHoles = viewLine.findViewById(R.id.numberOfPowerHoles)

       lineNumberEt = viewLine.findViewById(R.id.lineNumberEt)
       shenyuNumber = viewLine.findViewById(R.id.shenyuNumber)
       srcStateSp   = viewLine.findViewById(R.id.srcStateSp)
        ghYear   = viewLine.findViewById(R.id.ghYear)
        val yearHindLt:LinearLayout=viewLine.findViewById(R.id.yearHindLt)



        if (isLine.start_id != null) {
            App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(isLine.start_id)).list().let {
                roadStarTv.text = it[0].roadName
            }
            App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(isLine.end_id)).list().let {
                roadEndTv.text = it[0].roadName
            }
            isLine.moduleTxt.let {
                gridNameLineEt.setText(it)
            }
            isLine.dlzjSpec.let {
                zjcjgTv.setText(it)
            }
            //名称
            isLine.name.let {
                lineTvName.setText(it)
            }
            //道路主次路
            isLine.roadPands.let {
                roadZcEt.setText(it)
            }
            //道路位置
            isLine.roadAdress.let {
                roadAdress.setText(it)
            }
            //已占用数量
            isLine.ardUseNumer.let {
                lineNumberEt.setText(it)
            }
            //电力孔数
            isLine.electriHoleNumer.let {
                numberOfPowerHoles.text = it
            }
            isLine.remaNumber.let {
                shenyuNumber.setText(it)
            }
            isLine.roadUtili.let {
                resultHolesTv.text = it
            }
            isLine.srcYear.let {
                ghYear.setText(it)
            }



            val arrayListRs = resources.getStringArray(R.array.linsrcTypeArray)
            for (selecteIndex in arrayListRs.indices) {
                if (isLine.resType == null) {
                    srcNetureTypeSpiner.setSelection(0)
                    break
                }
                if (arrayListRs[selecteIndex] == isLine.resType) {
                    srcNetureTypeSpiner.setSelection(selecteIndex)
                    break
                }
            }
            srcNetureTypeSpiner.onItemSelectedListener = object : OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                    initSrcGuiGe(arrayListRs[position], isLine)
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {}
            }
        }

        val arrayListRs = resources.getStringArray(R.array.srState)
        for (selecteIndex in arrayListRs.indices) {
            if (isLine.state == null) {
                srcStateSp.setSelection(0)
                break
            }
            if (arrayListRs[selecteIndex] == isLine.state) {
                srcStateSp.setSelection(selecteIndex)
                break
            }
        }
        srcStateSp.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                if (arrayListRs[position] == "规划态") {
                    yearHindLt.visibility = View.VISIBLE
                } else {
                    yearHindLt.visibility = View.GONE
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }


        resultCaculateHols.setOnClickListener {
            if (!lineNumberEt.text.isNullOrEmpty() && !shenyuNumber.text.isNullOrEmpty()) {
                val str: String = format1(lineNumberEt.text.toString().toDouble() / (Integer.parseInt(lineNumberEt.text.toString()) + Integer.parseInt(shenyuNumber.text.toString())))
                resultHolesTv.text = str
            }
        }
        //endregion
        line_tv_line_hui!!.setText(isLine.backNum)
        line_tv_dj!!.setText(if (isLine.length != null) isLine.length else "")
        val equipList: List<Equip?> = getGuPiaoDai(3)
        //适配器
        val adapter: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this, android.R.layout.simple_spinner_item, equipList)
        //设置样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        line_sp_sort!!.adapter = adapter
        if (line_sp_sort!!.selectedItem.toString().contains("电缆")) {
            lineRlLaying!!.visibility = View.VISIBLE
        } else {
            lineRlLaying!!.visibility = View.GONE
        }
        for (i in equipList.indices) {
            if (isLine.type != null && (equipList[i]!!.getName().equals(isLine.type) || equipList[i]!!.getName().contains(isLine.type))) {
                line_sp_sort!!.setSelection(i)
                break
            }
        }
        if (isLine.state != null && !isLine.state.isEmpty()) {
            setSpinnerItemSelectedByValue(line_sp_statue, isLine.state)
        }
        if (isLine.pipe_laying_state != null && !isLine.pipe_laying_state.isEmpty()) {
            setSpinnerItemSelectedByValue(line_tongdao_statue, isLine.pipe_laying_state)
        }
        if (isLine.path != null && !isLine.path.equals("")) {
            Log.e("pathName", isLine.path)
            val linePath: Array<String> = getResources().getStringArray(R.array.laying)
            for (i in linePath.indices) {
                if (linePath[i].contains(isLine.path.trim())) {
                    Log.e("pathName", isLine.path + i)
                    lineSpLaying!!.setSelection(i)
                    break
                }
            }
        } else {
            setSpinnerItemSelectedByValue(lineSpLaying, "高压架空线路")
            line_tv_line_gen!!.setText("3")
            line_tv_line_gen!!.setEnabled(false)
        }
        line_sp_sort!!.setOnItemSelectedListener(object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                equip = line_sp_sort!!.getSelectedItem() as Equip
                modulesList = com.zj.osm.utils.db_utils.ModuleUtils.getInstance().getModuleList(equip!!.getId())
                //适配器
                val arr_adapter4: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this@LineActivity, android.R.layout.simple_spinner_item, modulesList)
                arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                line_sp_type!!.setAdapter(arr_adapter4)
                if (isLine.types != null) {
                    Log.e("types======ssss", isLine.types)
                    for (i in modulesList.indices) {
                        if (modulesList[i]!!.getModuleName().contains(isLine.types)) {
                            line_sp_type!!.setSelection(i)
                            break
                            //setSpinnerItemSelectedByValue(line_sp_type, isLine.getTypes());
                        }
                    }
                }
                if (line_sp_sort!!.getSelectedItem().toString().contains("电缆")) {
                    lineRlLaying!!.setVisibility(View.VISIBLE)
                } else {
                    lineRlLaying!!.setVisibility(View.GONE)
                }
                Log.e("equpName", equip!!.name)
                if (equip!!.getName().equals("高压架空线路")) {
                    line_tv_line_gen!!.setText("3")
                    line_tv_line_gen!!.setEnabled(true)
                } else if (equip!!.getName().equals("低压架空线路")) {
                    line_tv_line_gen!!.setText("4")
                    line_tv_line_gen!!.setEnabled(true)
                } else if (equip!!.getName().contains("电缆")) {
                    line_tv_line_gen!!.setText("1")
                    line_tv_line_gen!!.setEnabled(true)
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        })
        line_sp_type!!.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
                Log.e("TAG", "onItemSelectessd: " + modulesList[position]!!.toStrings())
                //如果是电缆，显示敷设方式。否则不显示
                if (modulesList[position]!!.getRemark() != null && !modulesList[position]!!.getRemark().equals("")) {
                    Log.e("pathName2", modulesList[position]!!.getRemark())
                    setSpinnerItemSelectedByValue(lineSpLaying, modulesList[position]!!.getRemark())
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        lineTvName.setText(isLine.name)
        if (isLine.item_id != null) {
            val pointList: List<Point?> = App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.ProjectId.eq(isLine.item_id)).build().list()
            Log.e("pointListWangfei=", pointList.toString());
            //适配器
            val sp_adapter: ArrayAdapter<Point?> = ArrayAdapter(this, android.R.layout.simple_spinner_item, pointList)
            sp_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            line_sp_a?.adapter = sp_adapter
            line_sp_b?.adapter = sp_adapter
            val ptA: Point = App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(isLine.start_id)).build().unique()
            Log.e("pointListWangfei01=", ptA.toString());

            val ptB: Point = App.getInstances().daoSession.pointDao.queryBuilder().where(PointDao.Properties.Uid.eq(isLine.end_id)).build().unique()
            Log.e("pointListWangfei02=", ptA.toString());

            if (ptA != null) {
                for (i in 0 until line_sp_a?.adapter!!.count) {
                    val spA: Point = line_sp_a?.adapter!!.getItem(i) as Point
                    if (ptA.uid.equals(spA.uid)) {
                        line_sp_a?.setSelection(i, true)
                    }
                }
            }
            if (ptB != null) {
                for (i in 0 until line_sp_b?.adapter!!.count) {
                    val spB: Point = line_sp_b?.adapter!!.getItem(i) as Point
                    if (ptB.getUid().equals(spB.getUid())) {
                        line_sp_b?.setSelection(i, true)
                    }
                }
            }
        }
        //显示柱上设备模态弹窗
        val dialogFushu = AlertDialog.Builder(context).create()
        dialogFushu.setView(viewLine)
        map_btn_cancell?.setOnClickListener{
            dialogFushu.dismiss()
            finish()
        }
        line_btn_save?.setOnClickListener(View.OnClickListener { v: View? ->
            if (lineTvName.getText().toString().trim { it <= ' ' }.isEmpty() || lineTvName.getText().toString().trim { it <= ' ' } == "" || lineTvName?.getText() == null) {
                ToastUtils.showShort("请输入线路名称")
            } else {
                if (lineTvName.text.toString().trim() == isLine.name) {
                    val dismiss = saveLine(isLine, false)
                    if (!dismiss) {
                        return@OnClickListener
                    }
                    dialogFushu.dismiss()
                    finish()
                } else {
                    dialogFushu.dismiss()
                    val dialog = NormalDialog(this@LineActivity)
                    dialog.content("修改整个线路名称为:" + "'" + lineTvName.text.toString().trim { it <= ' ' } + "'") //
                            .style(NormalDialog.STYLE_TWO) //
                            .btnNum(3)
                            .title("是否修改整条线路?")
                            .btnText("取消", "是", "否") //
                            .show()
                    dialog.setOnBtnClickL(OnBtnClickL { dialog.dismiss() }, OnBtnClickL {
                        dialog.dismiss()
                        saveLine(isLine, true)
                        dialogFushu.dismiss()
                        finish()
                    }, OnBtnClickL {
                        dialog.dismiss()
                        saveLine(isLine, false)
                        dialogFushu.dismiss()
                        finish()
                    })
                }
            }
        })
        dialogFushu.show()
    }

    private fun initSrcGuiGe(value: String, isLine: Line) {
        val arrayListRs: Array<String>;
        if (value == "电缆沟") {
            arrayListRs = resources.getStringArray(R.array.dlgArray)

        } else {
            arrayListRs = resources.getStringArray(R.array.paiZmArray)
        }
        //适配器
        val srcArrayAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayListRs)
        //设置样式
        srcArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        srcNetureSpiner.adapter = srcArrayAdapter
        for (selecteIndex in arrayListRs.indices) {
            if (isLine.resSpec == null) {
                srcNetureSpiner.setSelection(0)
                break
            }
            if (arrayListRs[selecteIndex] == isLine.resSpec) {
                srcNetureSpiner.setSelection(selecteIndex)
                break
            }
        }
    }

    private fun saveLine(isLine: Line, allAlert: Boolean) :Boolean {
        val allLineName = isLine.name
        if (lineTvName.text.toString().trim { it <= ' ' }.isEmpty() || lineTvName.text.toString().trim { it <= ' ' } == "" || lineTvName!!.text == null) {
            ToastUtils.showShort("请输入线路名称")
        } else {
            val ptA: Point = line_sp_a?.selectedItem as Point
            val ptB: Point = line_sp_b?.selectedItem as Point
            if (equip != null && equip != null) {
                isLine.typeId = (equip?.getId().toString() + "")
            }
            isLine.legendTypeKey = getLineRemarker(line_sp_sort!!.selectedItem.toString() + "")
            isLine.state = (line_sp_statue!!.selectedItem.toString().trim { it <= ' ' })
            isLine.pipe_laying_state = (line_tongdao_statue!!.selectedItem.toString().trim { it <= ' ' })
            isLine.latA = ptA.latitude.toString() + ""
            isLine.lonA = ptA.longitude.toString() + ""
            isLine.latB = ptB.latitude.toString() + ""
            isLine.lonB = ptB.longitude.toString() + ""
            isLine.name = lineTvName.text.toString()
            isLine.methodName = line_sp_sort?.selectedItem.toString() + ""
            isLine.start_id = ptA.getUid().toString() + ""
            isLine.end_id = ptB.getUid().toString() + ""
            isLine.length = line_tv_dj?.text.toString()
            if (line_tv_line_hui?.text.toString().trim { it <= ' ' } != "") {
                isLine.backNum = line_tv_line_hui!!.text.toString().trim { it <= ' ' }
            } else {
                isLine.backNum = "1"
            }
            if (line_tv_line_gen!!.text.toString().trim { it <= ' ' } != "") {
                Log.e("线路根数", line_tv_line_gen!!.text.toString().trim { it <= ' ' })
                isLine.num = line_tv_line_gen!!.text.toString().trim { it <= ' ' }
            } else {
                isLine.num = "1"
            }
            if (lineSpLaying!!.selectedItem != null && lineSpLaying!!.selectedItem.toString() != "" && lineSpLaying!!.visibility == View.VISIBLE) {
                isLine.path = lineSpLaying!!.selectedItem.toString()
            }

            //道路主次路
            if (roadZcEt.text.isNullOrEmpty()){
                ToastUtils.showLong("道路主次路不能为空")
                return false
            }else{
                isLine.roadPands=roadZcEt.text.toString()
            }
            if (roadAdress.text.isNullOrEmpty()){
                ToastUtils.showLong("道路主次路不能为空")
                return false
            }else{
                isLine.roadAdress= roadAdress.text.toString()
            }
            isLine.ardUseNumer=lineNumberEt.text.toString()
            isLine.electriHoleNumer=numberOfPowerHoles.text.toString()
            isLine.remaNumber=shenyuNumber.text.toString()
            isLine.roadUtili=resultHolesTv.text.toString()
            isLine.srcYear=ghYear.text.toString()
            if (gridNameLineEt.text!=null&&gridNameLineEt.text.toString().isEmpty()){
                ToastUtils.showLong("网格名称不能为空")
                return false
            }else{
                isLine.moduleTxt=gridNameLineEt.text.toString()
            }
            if (zjcjgTv.text!=null&&zjcjgTv.text.toString().isEmpty()){
                ToastUtils.showLong("电缆支架规格不能为空")
                return false
            }else{
                isLine.dlzjSpec=zjcjgTv.text.toString()
            }
            isLine.resType=srcNetureTypeSpiner.selectedItem.toString()
            isLine.resSpec=srcNetureSpiner.selectedItem.toString()

           //endRegion
            App.getInstances().getDaoSession().getLineDao().update(isLine)
            if (allAlert) {
                val lineAllNameSame: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Name.eq(allLineName)).build().list()
                for (l in lineAllNameSame) {
                    l.name = lineTvName.text.toString()
                    App.getInstances().getDaoSession().getLineDao().update(l)
                }
            }
           MapActivity.isProgressShow = true
        }
        xuanxinList.clear()
        setLineXuanxing()
        return true
    }

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) { //若工作完成，取消动画，初始化界面
        }
    }
    var lineLuMokuai: LinearLayout? = null
    private var addLineSave: TextView? = null
    var buiLuNameber: TextView? = null
    var linesAdapter: RecyclerView.Adapter<LinesAdapter.ViewHolder?>? = null
    private fun setLineXuanxing() { //这里查询所有的线
        val gulianLineCurrent: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(currentLine!!.start_id), LineDao.Properties.End_id.eq(currentLine!!.end_id)).build().list()
        val gulianLineOther: List<Line> = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(currentLine!!.end_id), LineDao.Properties.End_id.eq(currentLine!!.start_id)).build().list()
        xuanxinList.addAll(gulianLineCurrent)
        xuanxinList.addAll(gulianLineOther)
        buiLuNameber!!.text = xuanxinList.size.toString() + "回路"
        linesAdapter?.notifyDataSetChanged()
    }

    private fun getUUID(): String? {
        return UUID.randomUUID().toString() + ""
    }

    fun format1(value: Double): String {
        var bd = BigDecimal(value * 100)
        bd = bd.setScale(2, RoundingMode.HALF_UP)
        return bd.toString()
    }
}